package com.ogj.shiro.controller;


import com.ogj.shiro.entity.User;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;


@Controller
public class UserController {

    @RequestMapping("/user/hello")
    public String hello(Model model) {
        model.addAttribute("hello","world");
        model.addAttribute("hello2","world");
        return "test";
    }
    @RequestMapping("/noAuth")
    public String nuAuth(){
        return "noAuth";
    }
    /**
     * 测试thymeleaf
     *
     */
    @RequestMapping("/testThymeleaf")
    public String TestThymeleaf(Model model){
        model.addAttribute("username","asdasdas");
        return "test";
    }
    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }
    @RequestMapping("/update")
    public String update(){
        return "/user/update";
    }
    @RequestMapping("/to_login")
    public String to_Login(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(User user, RedirectAttributesModelMap model){
        System.out.println(user.toString());
        /**
         * 使用shiro编写认证操作
         */
        //1、获取Subject
        Subject subject= SecurityUtils.getSubject();

        //2、封装用户数据
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());

        //3、执行登陆方法
        try {
            subject.login(token); // ===>去到ShiroConfig的验证操作
            //登陆成功
            model.addFlashAttribute("msg","登陆成功");
            System.out.println("登陆成功");
            return "redirect:testThymeleaf";
        }catch (UnknownAccountException e){
            //登陆失败：用户名不存在
            model.addFlashAttribute("msg","用户名不存在");
            System.out.println("用户名不存在");
            return "redirect:/to_login";
        }catch (IncorrectCredentialsException e){
            //登陆失败：密码错误
            model.addFlashAttribute("msg","密码错误");
            System.out.println("密码错误");
            return "redirect:/to_login";
        }
    }
}
